//
//  RegisterViewController.m
//  智慧小区
//
//  Created by lab603 on 15/7/9.
//  Copyright (c) 2015年 Dreamsoul. All rights reserved.
//

#import "RegisterViewController.h"
#import "UserInfo.h"
#import "PPHttpTool.h"
#import "MJExtension.h"
#import "ActionSheetStringPicker.h"
#import "APIClient.h"
#import "Community.h"
#import "Tool.h"
#define TOP_PADDING 10.f
#define BOTTOM_PADDING 10.f
#define LEFT_PADDING 20.f
#define RIGHT_PADDING 20.f
@interface RegisterViewController ()<UIGestureRecognizerDelegate>
//背景
@property (nonatomic,weak)UIImageView *backgroundView;
//scrollView
@property (nonatomic,weak)UIScrollView *scrollView;
//选择小区
@property (nonatomic,weak)UIView *communityView;
//选择小区Label
@property (nonatomic,weak)UILabel *communityLabel;
//选择label
@property (nonatomic,weak)UILabel *chooseCommunity;
//小剪头
@property (nonatomic,weak)UIImageView *arrowView;

//帐号
@property (nonatomic,weak)UIView *accountView;
//帐号Label
@property (nonatomic,weak)UILabel *accountLabel;
//帐号TextField
@property (nonatomic,weak)UITextField *accountField;

//密码View
@property (nonatomic,weak)UIView *passwordView;
//密码Label
@property (nonatomic,weak)UILabel *passwordLabel;
//密码TextField
@property (nonatomic,weak)UITextField *passwordField;

//确认密码
@property (nonatomic,weak)UIView *reViewPasswordView;
//确认密码Label
@property (nonatomic,weak)UIView *reViewPasswordLabel;
//确认密码TextFeild
@property (nonatomic,weak)UITextField *reViewPasswordField;

//住址
@property (nonatomic,weak)UIView *addressView;
//住址Label
@property (nonatomic,weak)UIView *addressLabel;
//住址TextFeild
@property (nonatomic,weak)UITextField *addressField;

//登录Button
@property (nonatomic,weak)UIButton *registerButton;
//tip2
@property (nonatomic,weak)UILabel *tipTwoLabel;
//tip3
@property (nonatomic,weak)UILabel *tipThreeLabel;

//保存小区的数组
@property (nonatomic,strong)NSArray *communityArray;
//保存小区的代号
@property (nonatomic,copy)NSString *dbName;
//保存用户信息对象
@property (nonatomic,strong)UserInfo *userInfo;
@end

@implementation RegisterViewController
- (id)init{
    if (self = [super init]) {
        self.title = @"注册";
        self.view.backgroundColor = APP_BACK_COLOR;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //避免在ios7后出现导航栏遮挡视图
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    //添加控件
    [self addSubview];
    //设置属性
    [self setLayout];
}
/**
 *  设置属性
 */
- (void)setLayout{
    //scrollView
    _scrollView.frame = self.view.bounds;
    _scrollView.contentSize = (CGSize){ScreenWidth,568};
    //设置frame
    CGFloat VHeight = 35.f;
    //背景
    CGFloat backgroundX = 0;
    CGFloat backgroundY = 0;
    CGFloat backgroundW = ScreenWidth;
    //高度待定
    CGFloat backgroundH = 0;
    //小区view
    CGFloat communityViewX = LEFT_PADDING;
    CGFloat communityViewY = TOP_PADDING;
    CGFloat communityViewW = ScreenWidth - LEFT_PADDING*2;
    CGFloat communityViewH = VHeight;
    _communityView.frame = CGRectMake(communityViewX, communityViewY, communityViewW, communityViewH);
    //小区Label
    CGFloat communityLabelX = TOP_PADDING;
    CGFloat communityLabelY = TOP_PADDING;
    _communityLabel.frame = (CGRect){{communityLabelX,communityLabelY},self.communityLabel.bounds.size};
    //选择小区
    CGFloat chooseCommunityX = 85;
    CGFloat chooseCommunityY = 0;
    CGFloat chooseCommunityW = 180;
    CGFloat chooseCommunityH = VHeight;
    _chooseCommunity.frame = (CGRect)CGRectMake(chooseCommunityX, chooseCommunityY, chooseCommunityW, chooseCommunityH);
    //小箭头
    CGSize arrowViewSize = CGSizeMake(20, 20);
    CGFloat arrowViewX = communityViewW - TOP_PADDING - arrowViewSize.width;
    CGFloat arrowViewY = (VHeight - arrowViewSize.height)*0.5;
    _arrowView.frame = (CGRect){{arrowViewX,arrowViewY},arrowViewSize};
    
    //帐号View
    CGFloat accountX = communityViewX;
    CGFloat accountY = CGRectGetMaxY(_communityView.frame)+TOP_PADDING;
    CGFloat accountW = communityViewW;
    CGFloat accountH = VHeight;
    _accountView.frame = CGRectMake(accountX, accountY, accountW, accountH);
    //帐号Label
    CGFloat accountLabelX = TOP_PADDING;
    CGFloat accountLabelY = TOP_PADDING;
    _accountLabel.frame = (CGRect){{accountLabelX,accountLabelY},self.accountLabel.bounds.size};
    //帐号TextField
    //CGFloat accountFieldX = CGRectGetMaxX(_accountLabel.frame)+TOP_PADDING;
    CGFloat accountFieldX = 80;
    CGFloat accountFieldY = 0;
    CGFloat accountFieldW = accountW - accountFieldX;
    CGFloat accountFieldH = VHeight;
    _accountField.frame = CGRectMake(accountFieldX, accountFieldY, accountFieldW, accountFieldH);
    
    //密码View
    CGFloat passwordViewX = accountX;
    CGFloat passwordViewY = CGRectGetMaxY(_accountView.frame)+TOP_PADDING;
    CGFloat passwordViewW = communityViewW;
    CGFloat passwordViewH = VHeight;
    _passwordView.frame = CGRectMake(passwordViewX, passwordViewY, passwordViewW, passwordViewH);
    //密码Label
    CGFloat passwordLabelX = TOP_PADDING;
    CGFloat passwordLabelY = TOP_PADDING;
    _passwordLabel.frame = (CGRect){{passwordLabelX,passwordLabelY},self.passwordLabel.bounds.size};
    //密码TextField
    //CGFloat passwordFieldX = CGRectGetMaxX(_passwordLabel.frame)+TOP_PADDING;
    CGFloat passwordFieldX = accountFieldX;
    CGFloat passwordFieldY = 0;
    CGFloat passwordFieldW = passwordViewW - passwordFieldX;
    CGFloat passwordFieldH = VHeight;
    _passwordField.frame = CGRectMake(passwordFieldX, passwordFieldY, passwordFieldW, passwordFieldH);
    
    //确认密码View
    CGFloat reViewPasswordViewX = accountX;
    CGFloat reViewPasswordViewY = CGRectGetMaxY(_passwordView.frame)+TOP_PADDING;
    CGFloat reViewPasswordViewW = communityViewW;
    CGFloat reViewPasswordViewH = VHeight;
    _reViewPasswordView.frame = CGRectMake(reViewPasswordViewX, reViewPasswordViewY, reViewPasswordViewW, reViewPasswordViewH);
    //确认密码Label
    CGFloat reViewPasswordLabelX = TOP_PADDING;
    CGFloat reViewPasswordLabelY = TOP_PADDING;
    _reViewPasswordLabel.frame = (CGRect){{reViewPasswordLabelX,reViewPasswordLabelY},self.reViewPasswordLabel.bounds.size};
    //确认密码TextField
    //CGFloat reViewPasswordFieldX = CGRectGetMaxX(_reViewPasswordLabel.frame)+TOP_PADDING;
    CGFloat reViewPasswordFieldX = passwordFieldX;
    CGFloat reViewPasswordFieldY = 0;
    CGFloat reViewPasswordFieldW = reViewPasswordViewW - reViewPasswordFieldX;
    CGFloat reViewPasswordFieldH = VHeight;
    _reViewPasswordField.frame = CGRectMake(reViewPasswordFieldX, reViewPasswordFieldY, reViewPasswordFieldW, reViewPasswordFieldH);
    
    //住址View
    CGFloat addressViewX = accountX;
    CGFloat addressViewY = CGRectGetMaxY(_reViewPasswordView.frame)+TOP_PADDING;
    CGFloat addressViewW = communityViewW;
    CGFloat addressViewH = VHeight;
    _addressView.frame = CGRectMake(addressViewX, addressViewY, addressViewW, addressViewH);
    //住址Label
    CGFloat addressLabelX = TOP_PADDING;
    CGFloat addressLabelY = TOP_PADDING;
    _addressLabel.frame = (CGRect){{addressLabelX,addressLabelY},self.addressLabel.bounds.size};
    //住址TextField
    //CGFloat addressFieldX = CGRectGetMaxX(_addressLabel.frame)+TOP_PADDING;
    CGFloat addressFieldX = reViewPasswordFieldX;
    CGFloat addressFieldY = 0;
    CGFloat addressFieldW = addressViewW - addressFieldX;
    CGFloat addressFieldH = VHeight;
    _addressField.frame = CGRectMake(addressFieldX, addressFieldY, addressFieldW, addressFieldH);

    
    //下一步按钮
    CGFloat loginButtonX = addressViewX;
    CGFloat loginButtonY = CGRectGetMaxY(_addressView.frame)+TOP_PADDING;
    CGFloat loginButtonW = ScreenWidth - LEFT_PADDING*2;
    CGFloat loginButtonH = VHeight;
    _registerButton.frame = CGRectMake(loginButtonX, loginButtonY, loginButtonW, loginButtonH);
    //tip2
    CGFloat tipTwoLabelX = loginButtonX;
    CGFloat tipTwoLabelY = CGRectGetMaxY(_registerButton.frame)+TOP_PADDING;
    _tipTwoLabel.frame = (CGRect){{tipTwoLabelX,tipTwoLabelY},self.tipTwoLabel.frame.size};
    //tip3
    CGFloat tipThreeLabelX = CGRectGetMaxX(_tipTwoLabel.frame);
    CGFloat tipThreeLabelY = tipTwoLabelY;
    _tipThreeLabel.frame = (CGRect){{tipThreeLabelX,tipThreeLabelY},self.tipThreeLabel.frame.size};
    backgroundH = CGRectGetMaxY(_tipThreeLabel.frame)+TOP_PADDING;
    _backgroundView.frame = CGRectMake(backgroundX, backgroundY, backgroundW, backgroundH);

}
/**
 *  添加子控件
 */
- (void)addSubview{
    //scrollView
    UIScrollView *scrollview = [[UIScrollView alloc] init];
    [self.view addSubview:scrollview];
    self.scrollView = scrollview;
    //背景
    UIImageView *backgroundView = [[UIImageView alloc] init];
    backgroundView.backgroundColor = [UIColor whiteColor];
    backgroundView.userInteractionEnabled = YES;
    [self.scrollView addSubview:backgroundView];
    self.backgroundView = backgroundView;
    //小区View
    UIView *communityView=[[UIView alloc]init];
    communityView.backgroundColor=[UIColor whiteColor];
    communityView.layer.borderWidth = 0.5;
    communityView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [communityView.layer setCornerRadius:CORNER_RADIUS_8];
    [self.backgroundView addSubview:communityView];
    self.communityView = communityView;
    //小区Label
    UILabel *communityLabel = [[UILabel alloc] init];
    communityLabel.textColor=APP_WORD_COLOR_1;
    communityLabel.text=@"小区";
    [communityLabel setFont:[UIFont systemFontOfSize:14.4]];
    [communityLabel sizeToFit];
    [self.communityView addSubview: communityLabel];
    self.communityLabel = communityLabel;
    //选择label
    UILabel *chooseCommunity = [[UILabel alloc] init];
    chooseCommunity.textColor=APP_THEME_COLOR;
    chooseCommunity.text=@"请选择小区(点我)";
    [chooseCommunity setFont:[UIFont systemFontOfSize:16.0]];
    [chooseCommunity sizeToFit];
    //添加点击手势
    chooseCommunity.userInteractionEnabled = YES;
    [chooseCommunity addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseCommunityTapped)]];
    [self.communityView addSubview: chooseCommunity];
    self.chooseCommunity = chooseCommunity;
    //小剪头
    UIImageView *arrowView = [[UIImageView alloc] init];
    arrowView.image = [UIImage imageNamed:@"arrows_down_icon"];
    [self.communityView addSubview:arrowView];
    self.arrowView = arrowView;
    
    //帐号View
    UIView *accountView=[[UIView alloc]init];
    accountView.backgroundColor=[UIColor whiteColor];
    accountView.layer.borderWidth = 0.5;
    accountView.layer.borderColor = [APP_HINT_COLOR CGColor];
    [accountView.layer setCornerRadius:CORNER_RADIUS_8];
    [self.backgroundView addSubview:accountView];
    self.accountView = accountView;
    //帐号label
    UILabel *accountLabel = [[UILabel alloc] init];
    accountLabel.textColor=APP_WORD_COLOR_1;
    accountLabel.text=@"帐号";
    [accountLabel setFont:[UIFont systemFontOfSize:14.4]];
    [accountLabel sizeToFit];
    [self.accountView addSubview: accountLabel];
    self.accountLabel = accountLabel;
    //帐号field
    UITextField *accountField = [[UITextField alloc] init];
    accountField.placeholder = @"请输入帐号";
    accountField.textColor = RGBACOLOR(86,84,84,1);
    accountField.returnKeyType = UIReturnKeyDone;
    //accountField.keyboardType = UIKeyboardTypePhonePad;
    accountField.enablesReturnKeyAutomatically = YES;
    accountField.clearButtonMode = UITextFieldViewModeAlways;
    [accountField addTarget:self action:@selector(hidenKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.accountView addSubview:accountField];
    self.accountField = accountField;
    
    //密码View
    UIView *passwordView=[[UIView alloc]init];
    passwordView.backgroundColor=[UIColor whiteColor];
    passwordView.layer.borderWidth = 0.5;
    passwordView.layer.borderColor = [APP_HINT_COLOR CGColor];
    [passwordView.layer setCornerRadius:CORNER_RADIUS_8];
    [self.backgroundView addSubview:passwordView];
    self.passwordView = passwordView;
    //密码label
    UILabel *passwordLabel = [[UILabel alloc] init];
    passwordLabel.textColor=APP_WORD_COLOR_1;
    passwordLabel.text=@"密码";
    [passwordLabel setFont:[UIFont systemFontOfSize:14.4]];
    [passwordLabel sizeToFit];
    [self.passwordView addSubview: passwordLabel];
    self.passwordLabel = passwordLabel;
    //密码field
    UITextField *passwordField = [[UITextField alloc] init];
    passwordField.placeholder = @"请输入密码";
    passwordField.textColor = RGBACOLOR(86,84,84,1);
    passwordField.secureTextEntry = YES;
    passwordField.returnKeyType = UIReturnKeyDone;
    //passwordField.keyboardType = UIKeyboardTypePhonePad;
    passwordField.enablesReturnKeyAutomatically = YES;
    passwordField.clearButtonMode = UITextFieldViewModeAlways;
    [passwordField addTarget:self action:@selector(hidenKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.passwordView addSubview:passwordField];
    self.passwordField = passwordField;
    
    //确认密码
    UIView *reViewPasswordView=[[UIView alloc]init];
    reViewPasswordView.backgroundColor=[UIColor whiteColor];
    reViewPasswordView.layer.borderWidth = 0.5;
    reViewPasswordView.layer.borderColor = [APP_HINT_COLOR CGColor];
    [reViewPasswordView.layer setCornerRadius:CORNER_RADIUS_8];
    [self.backgroundView addSubview:reViewPasswordView];
    self.reViewPasswordView = reViewPasswordView;
    //密码label
    UILabel *reViewPasswordLabel = [[UILabel alloc] init];
    reViewPasswordLabel.textColor=APP_WORD_COLOR_1;
    reViewPasswordLabel.text=@"确认密码";
    [reViewPasswordLabel setFont:[UIFont systemFontOfSize:14.4]];
    [reViewPasswordLabel sizeToFit];
    [self.reViewPasswordView addSubview: reViewPasswordLabel];
    self.reViewPasswordLabel = reViewPasswordLabel;
    //密码field
    UITextField *reViewPasswordField = [[UITextField alloc] init];
    reViewPasswordField.placeholder = @"请确认输入密码";
    reViewPasswordField.textColor = RGBACOLOR(86,84,84,1);
    reViewPasswordField.secureTextEntry = YES;
    reViewPasswordField.returnKeyType = UIReturnKeyDone;
    //passwordField.keyboardType = UIKeyboardTypePhonePad;
    reViewPasswordField.enablesReturnKeyAutomatically = YES;
    reViewPasswordField.clearButtonMode = UITextFieldViewModeAlways;
    [reViewPasswordField addTarget:self action:@selector(hidenKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.reViewPasswordView addSubview:reViewPasswordField];
    self.reViewPasswordField = reViewPasswordField;
    
    //住址
    UIView *addressView=[[UIView alloc]init];
    addressView.backgroundColor=[UIColor whiteColor];
    addressView.layer.borderWidth = 0.5;
    addressView.layer.borderColor = [APP_HINT_COLOR CGColor];
    [addressView.layer setCornerRadius:CORNER_RADIUS_8];
    [self.backgroundView addSubview:addressView];
    self.addressView = addressView;
    //住址label
    UILabel *addressLabel = [[UILabel alloc] init];
    addressLabel.textColor=APP_WORD_COLOR_1;
    addressLabel.text=@"住址";
    [addressLabel setFont:[UIFont systemFontOfSize:14.4]];
    [addressLabel sizeToFit];
    [self.addressView addSubview: addressLabel];
    self.addressLabel = addressLabel;
    //住址field
    UITextField *addressField = [[UITextField alloc] init];
    addressField.placeholder = @"请输入您的住址";
    addressField.textColor = RGBACOLOR(86,84,84,1);
    //addressField.secureTextEntry = YES;
    addressField.returnKeyType = UIReturnKeyDone;
    //passwordField.keyboardType = UIKeyboardTypePhonePad;
    addressField.enablesReturnKeyAutomatically = YES;
    addressField.clearButtonMode = UITextFieldViewModeAlways;
    [addressField addTarget:self action:@selector(hidenKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.addressView addSubview:addressField];
    self.addressField = addressField;
    
    //登录按钮
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    registerButton.layer.borderWidth = 1;
    registerButton.layer.borderColor = [APP_HINT_COLOR CGColor];
    [registerButton.layer setCornerRadius:CORNER_RADIUS_8];
    registerButton.backgroundColor=APP_THEME_COLOR;
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    registerButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [registerButton addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundView addSubview: registerButton];
    self.registerButton = registerButton;
    //tip2
    UILabel *tipTwoLabel = [[UILabel alloc] init];
    tipTwoLabel.textColor=APP_WORD_COLOR_2;
    tipTwoLabel.text=@"注册表示已阅读并同意";
    [tipTwoLabel setFont:[UIFont systemFontOfSize:9.6]];
    [tipTwoLabel sizeToFit];
    [self.backgroundView addSubview: tipTwoLabel];
    self.tipTwoLabel = tipTwoLabel;
    
    //tip3
    UILabel *tipThreeLabel = [[UILabel alloc] init];
    tipThreeLabel.textColor=APP_THEME_COLOR;
    tipThreeLabel.text=@"用户服务协议";
    [tipThreeLabel setFont:[UIFont systemFontOfSize:9.6]];
    [tipThreeLabel sizeToFit];
    [self.backgroundView addSubview: tipThreeLabel];
    [tipThreeLabel setUserInteractionEnabled:YES];
    [tipThreeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showProtocol)]];
    
    self.tipThreeLabel = tipThreeLabel;
    
    //添加手势，点击屏幕其他区域关闭键盘的操作
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyboard)];
    gesture.numberOfTapsRequired = 1;
    gesture.delegate = self;
    [self.view addGestureRecognizer:gesture];
}
/**
 *  注册按钮被点击
 */
- (void)registerBtnClick{
    //判断注册条件是否符合
    if (self.dbName==nil) {
        [Tool HUDShowMessage:@"请选择小区"];
        return;
    }
    if ([self.accountField.text isEqualToString:@""]) {
        [Tool HUDShowMessage:@"请输入帐号"];
        return;
    }
    if (self.accountField.text.length>16){
        [Tool HUDShowMessage:@"帐号不合法，1-16位字符..."];
        return;
    }
    if ([self.passwordField.text isEqualToString:@""]) {
        [Tool HUDShowMessage:@"请输入密码"];
        return;
    }
    if (![self isPasswordRight:self.passwordField.text]) {
        [Tool HUDShowMessage:@"密码不合法，6-16位字符"];
        return;
    }
    if (![self.passwordField.text isEqualToString:self.reViewPasswordField.text]) {
        [Tool HUDShowMessage:@"两次输入的密码不一致"];
        return;
    }
    if ([self.addressField.text isEqualToString:@""]) {
        [Tool HUDShowMessage:@"请输入地址"];
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"user"] = self.accountField.text;
    params[@"pwd"] = self.passwordField.text;
    params[@"room"] = self.addressField.text;
    params[@"place"] = self.dbName;
    params[@"role"] = @1;
    NSString *urlString = [APIClient relativePathForRegister];
    [PPHttpTool postWithURL:urlString params:params success:^(id json) {
        IWLog(@"%@",json);
        if ([json[@"resultCode"] isEqual:@1]) {
            [MBProgressHUD showSuccess:@"注册成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [Tool HUDShowMessage:@"注册失败"];
        }
    } failure:^(NSError *error) {
        [Tool HUDShowMessage:@"注册失败"];
    }];
}
/**
 *  隐藏键盘
 */
- (void)hidenKeyboard{
    [self.view endEditing:YES];
}
/**
 *  显示协议
 */
- (void)showProtocol{
    
}
/**
 *  选择小区
 */
- (void)chooseCommunityTapped{
    NSString *urlString = [APIClient relativePathForCommunity];
    IWLog(@"%@",urlString);
    NSMutableArray *tempArray = [NSMutableArray array];
    [PPHttpTool getWithURL:urlString params:nil success:^(id json) {
        IWLog(@"%@",json);
        self.communityArray = [Community objectArrayWithKeyValuesArray:json];
        //得到要展示的小区数组
        for (int i = 0; i<self.communityArray.count; i++) {
            Community *community = self.communityArray[i];
            [tempArray addObject:community.communityName];
        }
        //创建pickerView
        [ActionSheetStringPicker showPickerWithTitle:@"请选择小区" rows:tempArray initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
            IWLog(@"%ld,%@",(long)selectedIndex,selectedValue);
            self.chooseCommunity.textColor = [UIColor blackColor];
            self.chooseCommunity.text = selectedValue;
            Community *community = self.communityArray[selectedIndex];
            self.dbName = community.dbName;
        } cancelBlock:^(ActionSheetStringPicker *picker) {
            
        } origin:self.view];
    } failure:^(NSError *error) {
        [Tool HUDShowMessage:@"无法连接服务器"];
        return ;
    }];
    
}
/**
 *  判断密码是否合法
 */
- (BOOL)isPasswordRight:(NSString *)password{
    if (password.length<6|password.length>16) {
        return NO;
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
